/**
 * @file 中间件处理工具
 */
import { IncomingMessage, ServerResponse, RequestListener } from "http"
import { MiddlewareFunction, MiddlewareNext, MiddlewareOptions, ExtraMiddlewareOptions } from "../../index.d.js"

/** 迭代中间件列表, 进行组合
 *
 * @param middlewareList 中间件列表
 * @param options 用于中间件之间传递的参数
 * @returns 返回组合后的请求回调
 */
function setMiddleware(middlewareList: MiddlewareFunction[], options: MiddlewareOptions) {
  let onRequest: MiddlewareFunction = () => {}

  function setMiddle(next: MiddlewareNext) {
    const current = middlewareList.pop()
    if (current) {
      const newNext = () => {
        current(options, next)
      }

      if (middlewareList.length) {
        setMiddle(newNext)
      } else {
        onRequest = newNext
      }
    }
  }
  setMiddle(() => {}) // 设置中间件

  return onRequest
}

/** 合并中间件
 *
 * @param middlewareList 中间件列表, 通过 app.use 插入
 * @param extraOptions 中间件之间传输的额外参数对象
 * @returns 返回一个用于 on("request") 的监听回调
 */
export function combineMiddleware(middlewareList: MiddlewareFunction[], extraOptions: ExtraMiddlewareOptions): RequestListener {
  return (request: IncomingMessage, response: ServerResponse) => {
    if (middlewareList.length) {
      const options = { request, response, ...extraOptions }
      const onRequest = setMiddleware([...middlewareList], options)
      onRequest(options, () => {})
    }
  }
}
